/*
 * VHMain.java
 * Created on 25 mai 2009
 *
 * VirtualHockey Internet Platform
 * http://code.google.com/p/virtualhockey/
 *
 * Copyright (c) 2005-2010, Jens and Jan Janke (VirtualHockey Project)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package com.hockeo.client;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HtmlContainer;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.hockeo.client.model.LoginStatus;
import com.hockeo.client.res.AppConstants;
import com.hockeo.client.ui.base.VHCenterPanelContent;
import com.hockeo.client.ui.widgets.MainMenuTree;
import com.hockeo.shared.rpc.classic.IRpcClassicService;
import com.hockeo.shared.rpc.classic.IRpcClassicServiceAsync;
import com.hockeo.shared.rpc.classic.RpcCallback;

/**
 * Main class of the VirtualHockey GUI.
 *
 * @version $Id$
 * @author jjanke
 */
public class VHMain implements EntryPoint
{
  public static final AbstractImagePrototype ICON_ACCEPT      = IconHelper.createPath( "images/icons/accept.png", 16,
                                                                  16 );
  public static final AbstractImagePrototype ICON_CANCEL      = IconHelper.createPath( "images/icons/cancel.png", 16,
                                                                  16 );
  public static final AbstractImagePrototype ICON_EDIT        = IconHelper.createPath( "images/icons/edit.png", 16, 16 );
  public static final AbstractImagePrototype ICON_ADD         = IconHelper.createPath( "images/icons/add.png", 16, 16 );
  public static final AbstractImagePrototype ICON_DELETE      = IconHelper.createPath( "images/icons/delete.png", 16,
                                                                  16 );
  public static final AbstractImagePrototype ICON_OFFICE      = IconHelper.createPath( "images/icons/house.png", 16, 16 );
  public static final AbstractImagePrototype ICON_COUNTRIES   = IconHelper.createPath( "images/icons/globe.png", 16, 16 );
  public static final AbstractImagePrototype ICON_SETTINGS    = IconHelper.createPath( "images/icons/settings.png", 16,
                                                                  16 );
  public static final AbstractImagePrototype ICON_BULLET_BLUE = IconHelper.createPath( "images/icons/bullet_blue.png",
                                                                  16, 16 );
  public static final String                 URL_MAIN_PAGE    = "/index.html";

  private static VHMain                      d_instance;
  private static AppConstants                d_resAppConstants;
  private static IRpcClassicServiceAsync     d_rpcClassic;

  private Viewport                           d_viewport;
  private ContentPanel                       d_pnWest;
  private ContentPanel                       d_pnCenter;
  private MainMenuTree                       d_mainMenu;

  /**
   * Returns the currently active instance of the VHMain GWT module.
   */
  public static VHMain get()
  {
    return d_instance;
  }

  public static AppConstants getAppConstants()
  {
    if ( d_resAppConstants == null )
      d_resAppConstants = GWT.create( AppConstants.class );

    return d_resAppConstants;
  }

  public static IRpcClassicServiceAsync getRpcClassicService()
  {
    if ( d_rpcClassic == null )
      d_rpcClassic = (IRpcClassicServiceAsync) GWT.create( IRpcClassicService.class );

    return d_rpcClassic;
  }

  /**
   * Sets the content of the center panel.
   *
   * @param widget the widget to be set as center panel
   */
  public void setCenterContent( Widget widget )
  {
    if ( widget instanceof VHCenterPanelContent )
      ( (VHCenterPanelContent) widget ).customiseParent( d_pnCenter );

    d_pnCenter.removeAll();
    d_pnCenter.add( widget );
    d_pnCenter.layout();
  }

  /**
   * This is the entry point method.
   */
  public void onModuleLoad()
  {
    // save module instance
    //
    d_instance = this;

    // build UI
    //
    d_viewport = new Viewport();
    d_viewport.setLayout( new BorderLayout() );

    createNorth();
    createWest();
    createCenter();

    // Get rid of scrollbars, and clear out the window's built-in margin,
    // because we want to take advantage of the entire client area.
    //
    Window.enableScrolling( false );
    Window.setMargin( "0px" );

    RootPanel.get().add( d_viewport );

    // determine login status
    //
    checkLoginStatus();
  }

  /**
   * Asks the server what is the current login status and updates the display of the
   * currently connected user as well as the login/logout URL.
   */
  private void checkLoginStatus()
  {
    AsyncCallback<LoginStatus> cb = new RpcCallback<LoginStatus>() {
      @Override
      public void processResult( LoginStatus loginStatus )
      {
        Element el = DOM.getElementById( "loginLink" );
        Element elLink = DOM.createAnchor();

        elLink.setClassName( "vhLink" );
        elLink.setAttribute( "href", loginStatus.getUrl() );

        if ( loginStatus.getUserName() != null )
        {
          DOM.getElementById( "loginText" ).setInnerHTML( loginStatus.getUserName() );

          elLink.setInnerText( getAppConstants().logout() );
          el.appendChild( elLink );

          if ( loginStatus.isAdmin() )
            d_mainMenu.enableAdminNode();
        }
        else
        {
          elLink.setInnerText( getAppConstants().login() );
          el.appendChild( elLink );
        }
      }
    };

    getRpcClassicService().getLoginStatus( cb );
  }

  private void createNorth()
  {
    StringBuffer sb = new StringBuffer();
    sb.append( "<div id='page-header' class='x-small-editor'><table style='width: 100%;' " );
    sb.append( "cellpadding='0' cellspacing='0'><tr><td><div id='page-title'>VirtualHockey v" );
    sb.append( getAppConstants().getAppVersion() );
    sb.append( "</div></td><td style='text-align: right;'>" );
    sb.append( "<div id='loginStatus'><span id='loginText'></span>&nbsp;<span id='loginLink'></span></div>" );
    sb.append( "</td></tr></table></div>" );

    HtmlContainer htmlNorth = new HtmlContainer( sb.toString() );

    BorderLayoutData data = new BorderLayoutData( LayoutRegion.NORTH, 33 );
    d_viewport.add( htmlNorth, data );
  }

  private void createWest()
  {
    d_pnWest = new ContentPanel();
    d_pnWest.setLayout( new FitLayout() );
    d_pnWest.setHeading( getAppConstants().navHeader() );

    ToolBar toolBar = new ToolBar();
    d_pnWest.setTopComponent( toolBar );

    // main menu tree
    //
    d_mainMenu = new MainMenuTree();
    d_pnWest.add( d_mainMenu );

    BorderLayoutData data = new BorderLayoutData( LayoutRegion.WEST, 270, 180, 320 );
    data.setMargins( new Margins( 5, 5, 5, 5 ) );
    data.setCollapsible( true );
    d_viewport.add( d_pnWest, data );
  }

  private void createCenter()
  {
    d_pnCenter = new ContentPanel();
    d_pnCenter.setLayout( new FitLayout() );

    ToolBar toolBar = new ToolBar();
    d_pnCenter.setTopComponent( toolBar );

    BorderLayoutData data = new BorderLayoutData( LayoutRegion.CENTER );
    data.setMargins( new Margins( 5, 5, 5, 0 ) );
    data.setCollapsible( false );
    d_viewport.add( d_pnCenter, data );
  }
}
